﻿namespace CloudNinja.Metering.Tests.Provider
{
    using System;
    using System.Collections.Generic;

    using CloudNinja.Metering.Common;
    using CloudNinja.Metering.Common.Logging;
    using CloudNinja.Metering.Data.Models;
    using CloudNinja.Metering.Providers;
    using CloudNinja.Metering.Providers.AzureBlob;
    using CloudNinja.Metering.Tests.Support;

    using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

    using Moq;

    using Xunit;

    public class BlobBandwidthProviderTests
    {
        [Fact(Timeout = -1)]
        public void CanReadBlobBanwidth()
        {
            var storageAccounts = new Dictionary<string, TenantsStorageAccount> {
                    {
                        "cn-tenantstore",
                        new TenantsStorageAccount
                            {
                                ConnectionString = GlobalTestSettings.StorageConnectionString,
                                TenantIdPattern = "tnt[ps]-{.+}"
                            }
                    }
                };

            var loggerMock = new Mock<ILogger>();
            loggerMock.Setup(l => l.LogException(It.IsAny<Exception>()));
            loggerMock.Setup(l => l.LogError(It.IsAny<string>()));
            loggerMock.Setup(l => l.LogInformation(It.IsAny<string>()));

            var repository = new List<MeterData>();

            var meteringRepositoryMock = new MeteringRepositoryMock(repository);

            var meteringContextMock = new Mock<IMeteringContext>();
            var retryStrategy = new Incremental();
            var retryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

            var stateRepository = new Mock<IParserBookmarkRepository>();
            stateRepository.Setup(s => s.GetBookmark(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(new ParserBookmark { LastLineParsed = 1, LastTimeParsed = DateTime.UtcNow.AddHours(-2) });

            meteringContextMock.Setup(mc => mc.AzureStorageRetryPolicy).Returns(retryPolicy);

            var provider = new BlobBandwidthProvider(
                TimeSpan.FromMinutes(1),
                storageAccounts,
                loggerMock.Object,
                stateRepository.Object,
                meteringRepositoryMock,
                meteringContextMock.Object);
           
            provider.Collect();

            stateRepository.Verify(s => s.SetBookmark(It.IsAny<ParserBookmark>()), Times.AtLeastOnce());
            Assert.True(repository.Count > 0);
        }
    }
}
